import os
import pymysql
import json
import paramiko as pm
from datetime import datetime, timedelta
from paramiko.client import SSHClient, AutoAddPolicy
difDb = pymysql.connect(host='10.2.5.100', port=13306, user='root', password='kc@#2023++', db="kcdoc")
dif_cursor = difDb.cursor()




target_host = '172.16.10.221'
target_port = 22
target_username = 'root'
target_password = 'Kc@123456'

# 创建SSH客户端对象
ssh_client1 = pm.SSHClient()
ssh_client1.set_missing_host_key_policy(pm.AutoAddPolicy())
ssh_client1.connect('127.0.0.1', port=22022, username='root', password='Kc@123456')
transport = ssh_client1.get_transport()
dest_addr = (target_host, target_port)
local_addr = ('', 0)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)

target_client = SSHClient()
target_client.set_missing_host_key_policy(AutoAddPolicy())
target_client.connect(target_host, port=target_port, username=target_username, password=target_password, sock=channel)
mainFtp = target_client.open_sftp()



# 创建SSH客户端对象
ssh_client2 = pm.SSHClient()
ssh_client2.set_missing_host_key_policy(pm.AutoAddPolicy())
ssh_client2.connect('10.2.5.100', port=9999, username='root', password='Kcadmin@123456')
appFtp = ssh_client2.open_sftp()


def diff_file(date):
    error_file = """
                     SELECT relative_path FROM sys_att_t WHERE (file_size > 98989.00 or file_name like '%.pdf' or file_name like '%.docx' ) and create_time > '{}'    ORDER BY create_time
                """.format(date)
    # error_file = """
    #                   SELECT relative_path FROM sys_att_t WHERE (file_size > 98989.00 or file_name like '%.pdf' or file_name like '%.docx' ) and create_time > '2024-04-30 00:00:00'    ORDER BY create_time
    #              """.format(date)

    mainFilePath = '/disk200/kcdoc/file/'
    appFilePath = '/data/kc_jf/file'
    diffPath = 'D:\\woker_file\\709\\file\\JFPlan\\'

    dif_cursor.execute(error_file)
    main_info = dif_cursor.fetchall()
    for e in main_info:
        print(e[0])
        split = e[0].split("/")
        maimFile = mainFilePath + split[0]
        try:
          file_attr = appFtp.stat(appFilePath + '/' + e[0])
          appFtp.get(appFilePath + '/' + e[0], diffPath +  split[1])
          mainFtp.put(diffPath + split[1], maimFile + '/' + split[1])
          os.remove(diffPath + split[1])
        except FileNotFoundError:
          print("文件不存在:"+e[0])




if __name__ == '__main__':
    diff_file()